import mqtt from "mqtt";
import Vue from 'vue'

var vm = new Vue();

class mqttHandle {
  constructor(subscribe) {
    this.connect = {
      host: "test.jiaoguanyi.cn",
      port: 443,           // 这里用了ngnix反向代理解决wss连接异常的问题
      endpoint: "/mqtt",
      clean: true, // 保留会话
      cleanSession: true,
      connectTimeout: 7000, // 超时时间 ms
      reconnectPeriod: 7000, // 重连时间间隔 ms
      // 认证信息
      clientId: Number(new Date()).toString(),
      username: "",
      password: "",
    }
    this.subscription = {
      topic: subscribe,  //需要传入数组的包含订阅的名称
      qos: 0,
    }
    this.mqttClient = null;
  }

  /**
   * 创建链接
   * @returns client
   */
  createConnect() {
    try {
      const {host, port, endpoint, ...options} = this.connect;
      const connectUrl = `wss://${this.connect.host}:${this.connect.port}${this.connect.endpoint}`;
      this._client = mqtt.connect(connectUrl, options);
      if (this._client.on) {
        this._client.on("connect", () => {
          console.log("Connection succeeded!");
        });
        this._client.on('reconnect', (error) => {
          console.log('正在重连', error)
        })
        this._client.on("error", (error) => {
          console.log("Connection failed", error);
        });
        //配置topic
        const {topic, qos} = this.subscription;
        this._client.subscribe(topic, {qos: qos}, (error, res) => {
          if (error) {
            console.log("Subscribe to topics error", error);
            return;
          }
        });
        this.mqttClient = this._client;
        return this.mqttClient;
      }
    } catch (error) {
      console.log("mqtt.connect error", error);
    }
  }

  generalCreateConnect() {
    try {
      const {host, port, endpoint, ...options} = this.connect;
      const connectUrl = `wss://${this.connect.host}:${this.connect.port}${this.connect.endpoint}`;
      this._client = mqtt.connect(connectUrl, options);
      if (this._client.on) {
        this._client.on("connect", () => {
          console.log("Connection succeeded!");
        });
        this._client.on('reconnect', (error) => {
          console.log('正在重连', error)
        })
        this._client.on("error", (error) => {
          console.log("Connection failed", error);
        });
        this.mqttClient = this._client;
        return this.mqttClient;
      }
    } catch (error) {
      console.log("mqtt.connect error", error);
    }
  }

  doPublish(topic, qos, payload) {
    this.mqttClient.publish(topic, payload, { qos }, error => {
      if (error) {
        console.log('Publish error', error)
      }
    })
  }



}

export default mqttHandle;
